<?php

namespace App\Extend;

use App\Exceptions\ApiException;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

class Phpoffice
{
    /**
     * 导入Excel文件.
     *
     * @param $file
     *
     * @return mixed
     */
    public static function import($file)
    {
        throw_if(empty($file), new ApiException('请选择上传文件'));

        $error = $file->getError();
        throw_if($error > 0, new ApiException('文件上传失败'));

        // 验证后缀
        $limit   = ['xls', 'xlsx'];
        $postfix = strtolower($file->getClientOriginalExtension());
        if ($postfix && !in_array($postfix, $limit)) {
            $str = implode(' | ', $limit);

            throw_if(true, new ApiException('只能上传 ' . $str . ' 格式的文件'));
        }

        $reader      = new Xlsx();
        $spreadsheet = $reader->load($file->getRealPath());

        return $spreadsheet->getActiveSheet()->ToArray();
    }
}
